package com.csstj.srm.controller;

import com.alibaba.druid.pool.DruidDataSource;
import com.csstj.srm.utils.DataSourceUtil;
import com.csstj.srm.common.dynamicDataSource.DBContextHolder;
import com.csstj.srm.entity.Demo;
import com.csstj.srm.service.DemoService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/demo/")
public class DemoController {

    //日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL，如果设置为WARN，则低于WARN的信息都不会输出。
    private final Logger logger = org.slf4j.LoggerFactory.getLogger(DemoController.class);

    @Autowired
    private DemoService demoService;

    @RequestMapping(value = "demo")
    public Map<String, String> demo(String token, String key) {
        Map<String, String> map = new HashMap<>();
        try {
            logger.trace("trace");
            logger.debug("debug");
            logger.info("info");
            logger.warn("warn");
            logger.error("error");
            DBContextHolder.setDataSource(key);
            Demo demo = demoService.selectByPrimaryKey(1);
            map.put("token", demo.toString());
            for (int i = 0; i < 100; i++) {
                final int finalI = i;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (finalI % 2 == 0) {
                            DBContextHolder.setDataSource("master");
                        } else {
                            DBContextHolder.setDataSource("slave");
                        }
                        Demo demo = demoService.selectByPrimaryKey(1);
                        logger.info("多线程查询：(i=" + finalI + "):" + demo.toString());
                    }
                }).run();
            }
        } catch (Exception e) {
            logger.error(e.toString());
            map.put("msg", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "add")
    public Map<String, String> add(String token) {
        Map<String, String> map = new HashMap<>();
        String key = "slave2";
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root");
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/test2");
        //添加数据源到map
        DataSourceUtil.addDataSource(key, druidDataSource);
        //刷新
        DataSourceUtil.flushDataSource();
        map.put("msg", "数据源数量:" + DataSourceUtil.dataSourceMap.size());
        return map;
    }
}
